﻿<?php

/**
 * Created by PhpStorm.
 * User: allen_ios
 * Date: 17/6/12
 * Time: 下午6:47
 */
class ZduRestaurantApiAction extends BaseAction
{
    public $resId; // 模块id
    public $restaurantId;
    public $iPadId;
    public $sRestaurant;
    public $accountId;
    public $mOrder;
    public $mLog;

    public function _initialize()
    {
//        parent::_initialize();
        $this->mOrder = M('RestaurantstyyOrder');
        $this->mLog = M('TestLog');
        import("@.ORG.RedisService");

        session('iPadId', $this->_request('iPad_id'));
        if(!in_array(strtolower(ACTION_NAME), array('addorder','notify','notify1','checkorderstatus','cancelorder','cardnotify','dealorder','getorder','saveorder','dopwd','getpaycode','addredis','qrcode'))){
            // 获取模块id
            $this->resId = $this->_request('res_id');
            // 获取餐厅id
            $this->restaurantId = $this->_request('restaurant_id');
            // 获取iPadId
            $this->iPadId = $this->_request('iPad_id');

            if (in_array(strtolower(ACTION_NAME), array('index'))) {
                if (!$this->resId || !$this->restaurantId) {
                    $this->ajaxReturn(array('code' => 10001, 'message' => '参数错误'));
                }
            }else{
                if (!$this->resId || !$this->restaurantId || !$this->iPadId ) {
                    $this->ajaxReturn(array('code' => 10002, 'message' => '参数错误'));
                }
            }
        }
        $this->accountId = 60;
    }


    /***
     * 测试 添加缓存
     */
    public function addRedis(){
        exit;
        $orderGoods = M('RestaurantstyyOrderGoods');
        $order = M('RestaurantstyyOrder');
        echo "<pre>";
        $num = 0;
        $num1 = 0;
        $data = $order->where(array('pay_time'=>array('between',array(1521676800,1521734399),'status'=>2)))->field('order_id,order_amount,goods_amount')->select();

        foreach($data as $k=>$v){
            if($v['order_amount']==0){
                $res = $order->where(array('order_id'=>$v['order_id']))->setField('order_amount',$v['goods_amount']);
                if($res){
                    $num1++;
                    var_dump($v['order_id']);
                }
            }
        }
        var_dump($num1);
        var_dump('********************************************');
        foreach($data as $k=>$v){
          $goods = $orderGoods->where(array('order_id'=>$v['order_id']))->select();
            if($v['goods_amount']==$v['order_amount']){
                  foreach($goods as $k1=>$v1){
                   $res = $orderGoods->where(array('og_id'=>$v1['og_id']))->setField('disconut_price',$v1['goods_price']);
                        if(!$res){
                          var_dump('*******');
                          var_dump($v1['order_id']);
                            var_dump('*******');
                        }else{
                            $num++;
                        }
                  }
            }else{
                foreach($goods as $k2=>$v2){
                  $info = array('disconut_price'=>$v2['goods_price']*0.8,'disconut'=>0.8);
                  $res = $orderGoods->where(array('og_id'=>$v2['og_id']))->setField($info);
                   if(!$res){
                       var_dump('----');
                      var_dump($v2['order_id']);
                       var_dump('----');
                   }else{
                       $num++;
                   }
                }
            }
        }
//        var_dump($order->_sql());
        var_dump($num);
    }





    /**
     * 获取缓存
     */
    public function getorder()
    {
        $redis = RedisQueueService::getInstance();
        $res = $redis->pull('styy_print');
        if($res){
            $this->ajaxReturn(array('code' => 200,'data'=>$res));
        }else{
            $this->ajaxReturn(array('code' => 300,'data'=>$res));
        }
    }


    /**
     * 获取菜品分类信息
     */
    public function index()
    {

        //获取菜品分类,调用service
        // 实例化服务类Service();第一个参数是文件路径:'ZdRestaurant/ZdRestaurant'
        $this->sRestaurant = Service('RestaurantStyy/BaseRestaurant','',array($this->resId,$this->restaurantId,$this->iPadId));
        // 查询改餐厅下所有的分类
        $allCategory = $this->sRestaurant->getCategory();
//        //并且返回当前店铺最热门的菜谱
//        $sGoods = Service('RestaurantStyy/BaseGoods');
//
//        $list = $sGoods->getHotGoods($this->restaurantId,$this->iPadId);
//        array_unshift($allCategory,$list);
        $this->ajaxReturn(array('code' => 200,'message' => '请求成功','data'=>$allCategory));
    }


    /**
     * 根据category_id获取分类下的菜品信息
     */
    public function getCategoryGoods(){

        $categoryId = $this->_request("category_id");

        $sGoods = Service('RestaurantStyy/BaseGoods');
        // 获取热门菜品-12份
        if ($categoryId==0){
            $list = $sGoods->getHotGoods($this->restaurantId);
        }else{
            $list = $sGoods->getGoods($categoryId,$this->resId);
        }

        if (!$list){
            $this->ajaxReturn(array('code' => 200,'message' => '没有菜品'));
        }

        $log=array(
            'content'=>"restaurantId=$this->restaurantId,categoryId=$categoryId,resId=$this->resId");
        M('TestLog')->add($log);
        $this->ajaxReturn(array('code' => 200,'message' => '请求成功','data'=>$list));

    }

    /**
     * 订单提交，生成支付宝二维码
     */
    public function AddOrder()
    {
        $post = json_decode($GLOBALS['HTTP_RAW_POST_DATA'],true);
        wLog(date("Y-m-d H:i:s")." kaishi: ".'*****************************',"styy");
        wLog(date("Y-m-d H:i:s")." AddOrder - 1: ".var_export($post,true),"styy");

        //检测商品的库存量
        $resId = $post['res_id'];
        $restaurantId = $post['restaurant_id'];
        $iPadId = $post['iPad_id'];
        if(!$resId||!$restaurantId||!$iPadId){
            $this->ajaxReturn(array('code'=>10003,'message'=>'参数错误'));
        }
        $goodsList = json_decode($post['goods'],true);
        wLog(date("Y-m-d H:i:s")." AddOrder - goodsList: ".var_export($goodsList,true),"styy");
        //判断购买商品数量是否为零
        foreach($goodsList as $k=>$v){
            if($v['goods_num']==0){
                unset($goodsList[$k]);
            }
        }
        //判断购物车是否为空
        if(count($goodsList)<1){
            $this->ajaxReturn(array('code'=>10004,'message'=>'购物车为空,请选择菜品'));
        }
        $sGoods = Service('RestaurantStyy/BaseGoods');

        //判断库存
        $checkRes = $sGoods->checkOrderStorage($goodsList);
        if(is_array($checkRes)){
            $this->ajaxReturn(array('code'=>10005,'message'=>'库存不足','data'=>$checkRes));
        }

        //生成订单号
        $orderSn = $this->getOrderSn('styyApi');
        //生成订单
        $data = array();
        $data['order_sn'] = $orderSn['data'];
        $data['order_num'] = 0;
        $data['status'] = 0;
        $data['user_id'] = 0;
        $data['res_id'] = $resId;
        $data['restaurant_id'] = $restaurantId;
        $data['create_time'] = time();
        $data['is_pay_notify'] = 0;
        $data['pay_type'] = 2;
        $data['sn'] = $iPadId;//机器sn号

        //往订单表插入数据
        $sOrder = Service('RestaurantStyy/BaseOrder');
        $ret = $sOrder->addOrder($data);

        if (!$ret){
            $this->ajaxReturn(array('code' => '10006','message' => '生成订单失败'));
        }
        $keyOrder = 'abc'.$ret;

        RedisService::set($keyOrder,$iPadId,86000);
        wLog(date("Y-m-d H:i:s")." AddOrder - keyOrder: ".var_export($keyOrder,true),"notify");
        wLog(date("Y-m-d H:i:s")." AddOrder - iPadId: ".var_export($iPadId,true),"notify");
        $sum = 0;
        foreach ($goodsList as $key=>$value){
            $goodsInfo = $sGoods->getGoodsInfo($this->resId,$this->restaurantId,$value['goods_id']);
            $sum+= $value['goods_num'] * $goodsInfo['price'];
            $orderGoodsInfo[] = array(
                'order_id' => $ret,
                'goods_id' => $value['goods_id'],
                'restaurant_id' => $restaurantId,
                'order_sn' => $orderSn['data'],
                'goods_num' => $value['goods_num'],
                'create_time' => time(),
                'user_id' => 0,
                'goods_name' => $goodsInfo['goods_name'],
                'goods_price' => $goodsInfo['price'],
                'goods_logo' => $goodsInfo['goods_logo'],
                'category_id' => $goodsInfo['category_id'],
                'window_id' => M('RestaurantstyyGoodsCategory')->where(array('category_id'=>$goodsInfo['category_id']))->getField('window_id'),
                'order_num' =>0,
                'print_type'=>$goodsInfo['print_type']
            );
        }
        $res = $sOrder->addGoodsAll($orderGoodsInfo);
        if (!$res){
            $this->ajaxReturn(array('code' => 10007,'message' => '插入订单物品失败'));
        }

        if($iPadId == 'T110175U00149'){
            $show = 1;
        }else{
            $show = $sum>50 ? 1:0;
        }

        // 更新订单 order_amount
        $data = array(
            'goods_amount'=>$sum,//商品原价
            'show'=>$show//商品原价

        );
        $updateOrder = $sOrder->updateOrder($ret,$data);
        if (!$updateOrder){
            $this->ajaxReturn(array('code' => 10008,'message' => '出错了'));
        }
        $array =array(
            'order_id'=>$ret,
            'order_sn'=>$orderSn['data'],
            'order_num'=>0,
            'order_amount'=> sprintf ("%01.2f",$sum),
            'isShow'=> $show ? true: false
        );
        wLog(date("Y-m-d H:i:s")." AddOrder-2-array: ".var_export($array,true),"styy");
        return $this->ajaxReturn(array('code' => 200,'message' => '生成订单成功','data'=>$array));

    }

    /*
     * 生成支付二维码
     * $type string  alipay:支付宝  onecard:一卡通
     * $orderSn string  订单号
     */
    public function getPayCode(){
       
        $post = $this->_post();

        if(!$post['order_sn']||!$post['type']){
            $this->ajaxReturn(array('code' => 10016,'message' => '请选择支付类型'));
        }
        $sOrder = Service('RestaurantStyy/BaseOrder');
        // 获取订单信息
        $orderInfo = $sOrder->getOrderInfo($post['order_id'],'order_sn,restaurant_id,order_num');
        if (!$orderInfo){
            $this->ajaxReturn(array('code' => 10011,'message' => '获取订单失败'));
        }
        if($post['type'] == 'alipay'){
            //生成支付宝二维码
            $sAlipay = Service("Pay/PayFactory");
            $resPay = $sAlipay->createObj('alipay',$this->accountId,$post['order_sn'],'浙大二食堂',$notifyUrl='',$returnUrl='',$ledger = array());
            $codePay = $resPay->codePay();

            $array =array(
                'order_sn'=>$post['order_sn'],
                'out_trade_no'=>$codePay['out_trade_no'],
                'pay_code'=>$codePay['qr_code']
            );
            $this->ajaxReturn(array('code' => 200,'message' => '生成支付宝订单成功','data'=>$array));
        }
        if($post['type'] =='oneCard'){
            //生成一个连接给Android端让其生成一个二维码
            $url = "http://wap.xt.beescrm.com/Restaurantstyy/ZduRestaurantApi/oneCardPayByAccount/order_id/".$post['order_id']."/res_id/".$this->resId."/restaurant_id/".$this->restaurantId."/iPad_id/".$this->iPadId;
            $array = array(
                'order_sn'=>$post['order_sn'],
                'out_trade_no'=>$post['order_sn'],
                'pay_code'=>$url
            );
            $this->ajaxReturn(array('code' => 200,'message' => '生成一卡通订单成功','data'=>$array));
        }
    }

    /*
     * 一卡通密码支付跳转页面
     */
    public function oneCardPayByAccount(){
        if($this->isGet()){
            $orderId = $this->_get('order_id');
            if(!$orderId){
                $this->error('系统繁忙，稍后重试！');
            }
            $this->assign('orderId',$orderId);
            $this->assign('resId',$this->resId);
            $this->assign('restaurantId',$this->restaurantId);
            $this->assign('iPadId',$this->iPadId);
            $this->display('onecardpay');
        }
        if($this->isAjax()){
            $resData = $this->_post();
            $orderId = $this->_post('order_id');
            //实例化模型
            $mOrderGoods= D('Base/RestaurantstyyOrderGoods');
            $mOrder = D('Base/RestaurantstyyOrder');

            //查询订单信息
            $info = $mOrder->relation(true)->getByPk($orderId);
            $orderGoodsArray = $mOrderGoods->field('goods_id,goods_num,goods_price,goods_name')->where(array('order_id'=>$orderId))->select();

            //模仿wika的代码
            $goodsNameCampusCard =array();
            foreach ($orderGoodsArray as $k=>$v){
                $goodsNameCampusCard[] = $v['goods_name'];
            }
            $resInfo = array('order_sn'=>$info['order_sn'],'order_num'=>$info['order_num'],'order_amount'=>$info['order_amount'],'pay_type'=>$info['pay_type'],'restaurant'=>'食天一隅点餐','goods_list'=>$orderGoodsArray);
            //跳转地址
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
            $redirectUrl = $protocol . $_SERVER['HTTP_HOST'];
            $thirdUrl = $redirectUrl . '/Restaurantstyy/ZduRestaurantApi/cardNotify/res_id/' . $this->resId."/restaurant_id/".$this->restaurantId;
            $errorUrl = $redirectUrl . '/Restaurantstyy/ZduRestaurantApi/cardErrorNotify/res_id/' . $this->resId."/restaurant_id/".$this->restaurantId;
            $goodsNameCampusCard = implode(',', $goodsNameCampusCard);
            $campus = Service('CampusCard/CampusCard');
            $resCampus = $campus->campusCardPay($this->accountId,$this->userId,$info, $thirdUrl, $errorUrl,2,$goodsNameCampusCard,$resData['account']);

            if ($resCampus['status'] == 'S') {
                $this->ajaxReturn(array('status'=>'S','message'=>'连接校园卡成功','data'=>$resCampus['data']));
            } else {
                $this->error('系统繁忙，稍后重试！');
            }
        }
    }

    /*
     * 校园卡刷卡确认支付
     */
    public function confirmPayByCard(){
        $account = $this->_post('account');
        /*$password = $this->_post('password');*/
        $orderId = $this->_post('order_id');
        if(!$account || !$orderId){
            $this->ajaxReturn(array('code' => 10017,'message' => '参数错误'));
        }
        //验证密码
        $verify = M('RestaurantstyyAccount')->where(array('account'=>$account,'cut_off'=>0))->find();
        if(!$verify){
            $this->ajaxReturn(array('code' => 10018,'message' => '口令错误'));
        }
        $this->notify($orderId,$type = 'PayByCard');
        $resInfo = $this->orderInfo($orderId);
        $this->ajaxReturn(array('code' => 200,'message' => '支付成功','data'=>$resInfo));
    }

    /*
     * 校园刷卡机支付确认
     */
    public function confirmPayBySchoolCard(){
        $orderId = $this->_post('order_id');
        $cardNumber = $this->_post('card_number');
        if(!$orderId){
            $this->ajaxReturn(array('code' => 10017,'message' => '参数错误'));
        }
//        M('TestLog')->add(array('content'=>$cardNumber,'num'=>1111));
        //更新订单里面的校园卡号。
        /*$campuscard = M("Campuscard")->where(array("account_id" => $this->accountId, "status" => 1))->find();
        vendor("CampusCard.CampusApiNew");
        $ser = new CampusApiNew($campuscard);
        $res = $ser->getAccountInfo($type = 'cardid',$cardNumber);
        $save = array(
            'card_number'=>$res['data'][0]['account']?$res['data'][0]['account']:'',
            'user_name'=>$res['data'][0]['name']?$res['data'][0]['name']:'',
        );
        M('RestaurantOrder')->where(array('order_id'=>$orderId))->save($save);*/
        $this->notify($orderId,$type ='PayBySchoolCard');
        $resInfo = $this->orderInfo($orderId);
//        M('TestLog')->add(array('content'=>$cardNumber,'num'=>2222));
        $this->ajaxReturn(array('code' => 200,'message' => '支付成功','data'=>$resInfo));
    }
    /*
     * 校园卡支付
     *回调
     */
    public function cardNotify(){
        if ($this->_post('thirdsystem')) { //校园卡支付
            $dataResonse = $_POST;
            if (!$dataResonse['sign']) {
                $this->error("参数错误");
            }
            $campus = Service('CampusCard/CampusCard');
            $resCampus = $campus->checkCampusOrder($dataResonse,2);
            if($resCampus['status'] == 'S'){
                $this->notify($resCampus['order_id'],'oneCard');
            }
        }

    }

    /*
     * 支付失败notify
     */
    public function cardErrorNotify(){
        echo 'GG思密达';
    }

    /**
     * 查询订单状态
     */
    public function checkOrderStatus(){

        $orderId = $this->_request("order_id");
        $outTradeNo = $this->_request("out_trade_no");
        $orderSn = $this->_request("order_sn");

        if (!$orderId||!$outTradeNo||!$orderSn){
            $this->ajaxReturn(array('code' => 10009,'message' => '参数错误'));
        }

        $sOrder = Service('RestaurantStyy/BaseOrder');
        $orderInfo = $sOrder->getOrderInfo($orderId,'order_sn,restaurant_id,order_num,pay_type,status');

        //一卡通支付与校园卡刷卡支付
        if($orderInfo['pay_type'] == 4||$orderInfo['pay_type'] == 5){
            if($orderInfo['status'] == 2){
                //通过订单id获取该订单对应的菜系
                $resInfo = $this->orderInfo($orderId);
                wLog(date("Y-m-d H:i:s")." checkOrderStatus-resInfo ".var_export($resInfo,true),"notify");
                $this->ajaxReturn(array('code' => 200,'message' => '支付成功','data'=>$resInfo));
            }else{
                $this->ajaxReturn(array('code' => 10010,'message' => '订单未支付'));
            }
        }
        // 查询订单状态
        $sAlipay = Service("Pay/PayFactory");
        $resPay = $sAlipay->createObj('alipay',$this->accountId,$orderSn,'浙大二食堂',$notifyUrl='',$returnUrl='',$ledger = array());
        $codePay = $resPay->orderQuery();
        //如果没有付款。返回的是false
        $tradeStatus = $codePay['data']['trade_status'];
        if($tradeStatus == 'WAIT_BUYER_PAY'){ //未支付
            $this->ajaxReturn(array('code' => 10010,'message' => '订单未支付'));
        }
        if($tradeStatus == 'TRADE_SUCCESS' || $tradeStatus == 'RADE_FINISHED'){ //支付成功
            //通过订单id获取该订单对应的菜系
            $resInfo = $this->orderInfo($orderId);
            wLog(date("Y-m-d H:i:s")." checkOrderStatus-resInfo1 ".var_export($resInfo,true),"notify");
            $this->ajaxReturn(array('code' => 200,'message' => '支付成功','data'=>$resInfo));
        }
        if($tradeStatus == 'TRADE_CLOSED'){ //已撤销或已退款
            $this->ajaxReturn(array('code' => 10014,'message' => '订单已关闭'));
        }
        //订单不存在
        if($codePay ==='ACQ.TRADE_NOT_EXIST'){
            $this->ajaxReturn(array('code' => 10015,'message' => '订单不存在'));
        }
    }

    /*
    * @param Int $orderId  订单号
    * return array
    */
    private function orderInfo($orderId){
        //通过订单id获取该订单对应的菜系
        $mOrderGoods= D('Base/RestaurantstyyOrderGoods');
        $mOrder = D('Base/RestaurantstyyOrder');
        $mInfo = D('Base/RestaurantstyyInfo');
//        $mGoods = D('Base/RestaurantstyyGoods');
//        $mGoodsCategory = D('Base/RestaurantstyyGoodsCategory');
        $restaurant_id = $mOrder->where(array('order_id'=>$orderId))->getField('restaurant_id');
        $restaurant_name = $mInfo->where(array('restaurant_id'=>$restaurant_id))->getField('restaurant_name');
        //查询订单信息
        $info = $mOrder->relation(true)->getByPk($orderId);
//        $goods = array();
        $orderGoodsArray = $mOrderGoods->field('goods_id,goods_num,goods_price,goods_name,print_type')->where(array('order_id'=>$orderId))->select();
//        $categoryIds = $mGoods->where(array('cut_off'=>0))->getField('goods_id,category_id');
//        $windowIds = $mGoodsCategory->where(array('cut_off'=>0))->getField('category_id,window_id');
//
//        foreach($orderGoodsArray as $k=>$v) {
//            $goods[$windowIds[$categoryIds[$v['goods_id']]]][] = $v;
//        }
        // $resInfo = array('order_sn' => $info['order_sn'], 'order_num' => $info['order_num'], 'order_amount' => $info['order_amount'],
        //     'goods_amount' => $info['order_amount']/0.8,'discount_amount' => $info['order_amount']*0.2,'pay_type' => $info['pay_type'], 'restaurant' => $restaurant_name, 'goods' => $orderGoodsArray);
        if($info['order_amount'] == 0.00){
            $resInfo = array('order_sn' => $info['order_sn'], 'order_num' => $info['order_num'], 'order_amount' => $info['goods_amount'],
                'goods_amount' => $info['goods_amount'],'discount_amount' => 0,'pay_type' => $info['pay_type'],
                'restaurant' => $restaurant_name, 'goods' => $orderGoodsArray);
        }else{
            $resInfo = array('order_sn' => $info['order_sn'], 'order_num' => $info['order_num'], 'order_amount' => $info['goods_amount'],
                'goods_amount' => $info['order_amount'],'discount_amount' => $info['goods_amount']-$info['order_amount'],'pay_type' => $info['pay_type'],
                'restaurant' => $restaurant_name, 'goods' => $orderGoodsArray);
        }

        return $resInfo;
    }

    /**
     * 取消订单
     */
    public function cancelOrder(){

        $orderId = $this->_request("order_id");
        $orderSn = $this->_request("order_sn");

        if (!$orderId||!$orderSn){
            $this->ajaxReturn(array('code' => 10009,'message' => '参数错误'));
        }
        $sOrder = Service('RestaurantStyy/BaseOrder');
        // 获取订单信息
        $orderInfo = $sOrder->getOrderInfo($orderId,'order_sn,restaurant_id,status');

        if (!$orderInfo){
            $this->ajaxReturn(array('code' => 10011,'message' => '获取订单失败'));
        }
        /*if ($orderInfo['status'] != 0 && $orderInfo['status'] != 7){
            $this->ajaxReturn(array('code' => 10012,'message' => '订单已完成或已取消'));
        }*/
        $sAlipay = Service("Pay/PayFactory");
        $resPay = $sAlipay->createObj('alipay',$this->accountId,$orderSn,'食天一隅点餐',$notifyUrl='',$returnUrl='',$ledger = array());
        $codePay = $resPay->orderReverse();
        if($codePay['status'] =='S'){
            //更新数据库
            $data = array('status'=>7);

            $res = $sOrder->updateOrder($orderId,$data);
            $this->ajaxReturn(array('code' => 200,'message' => '订单取消成功'));
        }else{
            $this->ajaxReturn(array('code' => 10013,'message' => '订单取消失败'));
        }
    }

    /**
     * 获取餐号
     */
    public function orderNum($iPadId=''){
        $array = array('T11017CS00277','T11017CS00305','T11717BJ00146'); //1楼 sn设备号

        $array1 = array('T11017CS00308','T11017CS00298'); //2楼

        $kafei = 'T11017CS00317'; //1楼咖啡吧
        $zzw = 'T110175U00149'; //2楼蒸之味
        $lef = 'T110175U00042'; //2楼卤儿饭

        if(in_array($iPadId,$array)){ //1楼点餐
            $key = '';
            $styyOrderNum = 'styyOrderNum5';
            $num = 'styyOrderNum6';
            $num1 = 0;
        }elseif(in_array($iPadId,$array1)){ //2楼点餐机
            $key = 'M';
            $styyOrderNum = 'styyOrderNum7';
            $num = 'styyOrderNum8';
            $num1 = 20000;
        }elseif($iPadId==$kafei){ //1楼咖啡点餐机
            $key = 'K';
            $styyOrderNum = 'styyOrderNum13';
            $num = 'styyOrderNum14';
            $num1 = 30000;
        }elseif($iPadId==$zzw){ //2楼蒸之味
            $key = 'Z';
            $styyOrderNum = 'styyOrderNum15';
            $num = 'styyOrderNum16';
            $num1 = 10000;
        }elseif($iPadId==$lef){//2楼卤儿饭
            $key = 'L';
            $styyOrderNum = 'styyOrderNum17';
            $num = 'styyOrderNum18';
            $num1 = 0;
        }
        //获取餐号
        $orderNum = RedisService::get($styyOrderNum);
        //不存在 给个默认值0
        if (!$orderNum) {
            RedisService::set($styyOrderNum, $num1);
        }
        //获取存的日期
        $time1 = RedisService::get($num);
        //不存在 给个默认值当前日期
        if (!$time1) {
            $time1 = RedisService::set($num, date('Y-m-d',time()));
        }
        //获取当前日期
        $time = date('Y-m-d',time());
        //存的日期和当前日期不一致 餐号归0 存的日期改成当天日期
        if($time != $time1){
            RedisService::set($styyOrderNum,$num1);
            RedisService::set($num,$time);
        }
        //餐号加1
        $orderNum = RedisService::incr($styyOrderNum);
        $orderNum = str_pad($orderNum,5,0,STR_PAD_LEFT );
        return $orderNum = $key.$orderNum;
    }


    /**
     * 支付回调-支付宝
     */
    public function notify($orderId,$type=''){
        $keyOrder = 'abc'.$orderId;
        wLog(date("Y-m-d H:i:s")." notify-keyOrder ".var_export($keyOrder,true),"notify");
        $iPadId =  RedisService::get($keyOrder);
        wLog(date("Y-m-d H:i:s")." notify-iPadId ".var_export($iPadId,true),"notify");
        //获取餐号
        $orderNum = $this->orderNum($iPadId);
        wLog(date("Y-m-d H:i:s")." notify-orderNum ".var_export($orderNum,true),"notify");

        if (!$orderId){
            exit('fail');
        }

        if($type == 'oneCard'){
            M('RestaurantstyyOrder')->where(array('order_id'=>$orderId))->save(array('status'=>2,'pay_type'=>4,'is_pay_notify'=>1,'pay_time'=>time(),'order_num'=>$orderNum));
        } else { //支付宝支付
            M('RestaurantstyyOrder')->where(array('order_id'=>$orderId))->save(array('status'=>2,'pay_type'=>5,'is_pay_notify'=>1,'pay_time'=>time(),'order_num'=>$orderNum));
        }
        wLog(date("Y-m-d H:i:s")." notify-_sql ".var_export(M('RestaurantstyyOrder')->_sql(),true),"notify");
        M('RestaurantstyyOrderGoods')->where(array('order_id'=>$orderId))->save(array('pay_status'=>1,'order_num'=>$orderNum));
        wLog(date("Y-m-d H:i:s")." notify-_sql ".var_export(M('RestaurantstyyOrderGoods')->_sql(),true),"notify");
        $sGoods = Service('RestaurantStyy/BaseGoods');
        // 减库存,加销量

        $sGoods->changeGoodsNum($orderId);
    }

    /**
     * 支付回调-校园卡
     */
    public function notify1($orderId,$type=''){

        $iPadId = session('iPadId');
        //获取餐号
        $orderNum = $this->orderNum($iPadId);

        if (!$orderId){
            exit('fail');
        }

        if($type == 'oneCard'){
            M('RestaurantstyyOrder')->where(array('order_id'=>$orderId))->save(array('status'=>2,'pay_type'=>4,'is_pay_notify'=>1,'pay_time'=>time(),'order_num'=>$orderNum));
        }elseif ($type == 'PayByCard'){
            M('RestaurantstyyOrder')->where(array('order_id'=>$orderId))->save(array('status'=>2,'pay_type'=>5,'is_pay_notify'=>1,'pay_time'=>time(),'order_num'=>$orderNum));
        }elseif ($type == 'PayBySchoolCard'){
            M('RestaurantstyyOrder')->where(array('order_id'=>$orderId))->save(array('status'=>2,'pay_type'=>6,'is_pay_notify'=>1,'pay_time'=>time(),'order_num'=>$orderNum));
        } else { //支付宝支付
            M('RestaurantstyyOrder')->where(array('order_id'=>$orderId))->save(array('status'=>2,'pay_type'=>5,'is_pay_notify'=>1,'pay_time'=>time(),'order_num'=>$orderNum));
        }

        M('RestaurantstyyOrderGoods')->where(array('order_id'=>$orderId))->save(array('pay_status'=>1,'order_num'=>$orderNum));

        $sGoods = Service('RestaurantStyy/BaseGoods');
        // 减库存,加销量

        $sGoods->changeGoodsNum($orderId);

        //通过订单id获取该订单对应的菜系
        /*        $mOrderGoods= D('Base/RestaurantstyyOrderGoods');
                $mOrder = D('Base/RestaurantstyyOrder');
                $mGoods = D('Base/RestaurantstyyGoods');
                $mGoodsCategory = D('Base/RestaurantstyyGoodsCategory');
                //查询订单信息
                $goods = array();
                $info = $mOrder->relation(true)->getByPk($orderId);
                $orderGoodsArray = $mOrderGoods->field('goods_id,goods_num,goods_price,goods_name,print_type')->where(array('order_id'=>$orderId))->select();
                $categoryIds = $mGoods->where(array('cut_off'=>0))->getField('goods_id,category_id');
                $windowIds = $mGoodsCategory->where(array('cut_off'=>0))->getField('category_id,window_id');
                foreach($orderGoodsArray as $k=>$v){
                    $goods[$windowIds[$categoryIds[$v['goods_id']]]][] = $v;
                }

                $printInfo = array('order_sn'=>$info['order_sn'],'order_num'=>$info['order_num'],'order_amount'=>$info['order_amount'],'pay_type'=>$info['pay_type'],'restaurant'=>'食天一隅点餐',
                    'push_time'=>time(),'goods'=>$goods);
                //每次将订单丢入到队列中，先进先出
                $redis = RedisQueueService::getInstance();
                $redis->push('styy_print',$printInfo);*/
    }
    /**
     * 生成二维码
     */
    public function qrcode()
    {
        $qr_code_message = $this->_get('qr_code');

        if (!$qr_code_message) {
            exit;
        }
//        $qr_code_message = 'https://qr.alipay.com/bax05291janmxz81hqzf0050';
        vendor('phpqrcode.phpqrcode');
        $errorCorrectionLevel = 'L';//容错级别
        $matrixPointSize = 12;//生成图片大小
        //生成二维码图片
        QRcode::png($qr_code_message, false, $errorCorrectionLevel, $matrixPointSize);
    }

    //检测某商品库存接口
    public function checkStorage(){
        $goodsId = $this->_request('goods_id');
        if(!$goodsId){
            $this->ajaxReturn(array('code'=>10001,'message'=>'参数错误'));
        }
        $mGoods = D('Base/RestaurantstyyGoods');
        $res = $mGoods->field('goods_id,goods_name,goods_sum')->where(array('goods_id' => $goodsId))->find();
        $this->ajaxReturn(array('code'=>200,'message'=>'获取商品库存成功','data'=>$res));
    }

    /**
     *打印信息
     * @param $orderId
     */
    public function useWifiPrintInfo($orderId)
    {
        //$orderId=8;
        $mOrder = D('Base/RestaurantstyyOrder');
        $mGoods = D('Base/RestaurantstyyGoods');
        $mWindow = D('Base/RestaurantstyyWindow');
        //$orderId = $this->_get('order_id');
        //查询订单信息
        $info = $mOrder->relation(true)->getByPk($orderId);
        //$info = $this->mOrder->relation(true)->getByPk($orderId);
        if ($info) {
            $goodsCold = array();
            $windowInfo = array();

            foreach ($info['RestaurantstyyOrderGoods'] as $key => $v) {
                //查询菜品对应的种类对应档口及打印机信息
                $list = $mGoods->relation('RestaurantstyyGoodsCategory')->getByPk($v['goods_id']);
                //$list = $this->mGoods->relation('RestaurantGoodsCategory')->getByPk($v['goods_id']);
                $wInfo = $mWindow->getByPk($list['window_id']);
                //$wInfo = $this->mWindow->getInfo($list['window_id']);
                $windowInfo[$wInfo['window_id']]['window_id'] = $wInfo['window_id'];
                $windowInfo[$wInfo['window_id']]['print_key'] = $wInfo['print_key'];
                $windowInfo[$wInfo['window_id']]['print_dno'] = $wInfo['print_dno'];
                $windowInfo[$wInfo['window_id']]['print_username'] = $wInfo['print_username'];
                $windowInfo[$wInfo['window_id']]['print_count'] = $wInfo['print_count'];
                $goodsCold[$v['window_id']][] = str_pad($v['goods_name'],18,'　'). str_pad($v['goods_num'],4).'￥'.number_format($v['goods_num']*$v['goods_price'],2)  . '\n';
                $windowInfo[$wInfo['window_id']]['order_amount'] += $v['goods_num']*$v['goods_price'];
                //$goodsHot = $goodsHot . $v['goods_name'] . '    ' . $v['goods_num'] . '     ' . $v['goods_num']*$v['goods_price'] . '\n';
            }
            foreach ($goodsCold as $one=>$on){
                $windowInfo[$one]['goods'] = implode('',$on);
            }
            $headerStr = '';
            if ($this->accountId == 2) {
                $headerStr = '|2http://weixin.qq.com/r/7UzVzQPEGF5nrUeu9xn-' . '\r\n';
            }
            if ($windowInfo) {
                if($info['pay_type'] == 1){
                    $payType = '微信';
                }
                if($info['pay_type'] == 2){
                    $payType = '支付宝';
                }
                if($info['pay_type'] == 4){
                    $payType = '一卡通';
                }
                if($info['pay_type'] == 5){
                    $payType = '校园卡';
                }
                foreach ($windowInfo as $val) {
                    $content = $headerStr .
                        '|5================================' . '\r\n' .
                        '|4餐厅名：' . $info['RestaurantInfo']['restaurant_name'] . '\r\n' .
                        '|4餐号：' . $info['order_num'] . '\r\n' .
                        '|5订单编号：' . $info['order_sn'] . '\r\n' .
                        '|5打印时间:'. date('Y-m-d H:i:s') . '\n' .
                        '|5支付方式:'. $payType . '\n' .
                        '|4------------------------' . '\n' .
                        str_pad('商品名称',18,'　').str_pad('数量',8).'小计'.'\n' .$val['goods'] .
                        '------------------------' . '\n' .
                        '总计：' . $val['order_amount'] .'元'. '\n';
                    $str = $val['print_key'] . $val['print_dno'] . 'aykj';
                    $keyInfo = md5($str);
                    $username = $val['print_username'];
                    $dno = $val['print_dno'];
                    $times = $val['print_count'];
                    $this->useWifiPrint($times, $keyInfo, $content, $username, $dno);
                }
            }
        }
    }

    /**
     *使用wifi打印机打印
     * @param int $times 打印次数
     * @param string $key 加密字符串
     * @param string $content 打印内容
     * @param string $username 官网用户名
     * @param string $dno 设备编号
     * @param int $mode 打印模式（0 混合打印;1文本打印; 2二维码打印;3条码打印）
     * @param string $msgno 订单编号（不传则自动生成）
     * @param string $op 操作类型（pf:打印操作  cx：查询打印机状态 cxdd：查询订单状态）
     * @param string $qr 支付宝二维码图片链接地址（可选）
     * @return array
     */
    function useWifiPrint($times = 3, $key, $content, $username, $dno, $mode = 0, $msgno = '', $op = 'pf', $qr = '')
    {
        /**
         * 返回状态码
         * 0 成功
         * 1 订单发送失败';
         * 200 查询失败';
         * 201 不存在当前设备';
         * 300 二维码打印成功';
         * 301 二维码打印失败';
         * 401 查询订单失败';
         * 900 没有相关操作';
         * 901 操作错误';
         * -2 验证错误';
         * -3 绑定设备不属于该用户';
         * -4 打印类型错误';
         * -5 该用户无效';
         * -7 设备号';
         * -8 参数错误';
         * -102 条形码打印存在汉字';
         * -103 组合打印类型不含有前缀';
         * .
        '序号：' . ($i + 1) . '\r\n' */

        $result = array();
        for ($i = 0; $i < $times; $i++) {
            $url = 'http://121.43.235.40/WS/DealData.ashx';
            $fields = array(
                'op' => $op,
                'content' => $content .
                    '|5================================' . '\r\n' .
                    '|4   青橄榄网络技术支持',
                'key' => $key,
                'unm' => $username,
                'dno' => $dno,
                'mode' => '|' . $mode,
                'msgno' => $msgno,
                'qr' => $qr,
            );
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, count($fields)); // 启用时会发送一个常规的POST请求，类型为：application/x-www-form-urlencoded，就像表单提交的一样。
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); // 在HTTP中的“POST”操作。如果要传送一个文件，需要一个@开头的文件名

            ob_start();
            curl_exec($ch);

            $result[] = ob_get_contents();
            ob_end_clean();
        }
        return $result;
    }


    /*
     * 打印服务，极光推送
     * @param $appKey String  app的key  android 提供
     * @param $masterSecret String app的密钥 Android 提供
     * @param $data array  需要推送的数据
     */
    public function aurora($appKey,$masterSecret,$data)
    {
        $appKey = '66bb204994df144f5f26a09e';
        $masterSecret = '8fbfd257d00f90c4673469c9';
        $logFile = '/logs';
        $retryTimes = 60;
        vendor('JPush.Client');
        $client = new Client($appKey, $masterSecret, $logFile, $retryTimes);
        try {
            $response = $client->push()
                ->setPlatform(array('ios', 'android'))
                // 一般情况下，关于 audience 的设置只需要调用 addAlias、addTag、addTagAnd  或 addRegistrationId
                // 这四个方法中的某一个即可，这里仅作为示例，当然全部调用也可以，多项 audience 调用表示其结果的交集
                // 即是说一般情况下，下面三个方法和没有列出的 addTagAnd 一共四个，只适用一个便可满足大多数的场景需求

                // ->addAlias('alias')
                ->addAllAudience()
                /*->addTag(array('tag1', 'tag2'))*/
                // ->addRegistrationId($registration_id)

                ->setNotificationAlert('Hi, JPush')
                ->iosNotification('Hello IOS', array(
                    'sound' => 'sound.caf',
                    // 'badge' => '+1',
                    // 'content-available' => true,
                    // 'mutable-content' => true,
                    'category' => 'jiguang',
                    'extras' => array(
                        'key' => 'value',
                        'jiguang'
                    ),
                ))
                ->androidNotification('Hello Android', array(
                    'title' => 'hello jpush',
                    // 'builder_id' => 2,
                    'extras' => array(
                        'key' => 'value',
                        'jiguang'
                    ),
                ))
                ->message('message content', array(
                    'title' => 'hello jpush',
                    // 'content_type' => 'text',
                    'extras' => array(
                        'key' => 'value',
                        'jiguang'
                    ),
                ))
                ->options(array(
                    // sendno: 表示推送序号，纯粹用来作为 API 调用标识，
                    // API 返回时被原样返回，以方便 API 调用方匹配请求与返回
                    // 这里设置为 100 仅作为示例

                    // 'sendno' => 100,

                    // time_to_live: 表示离线消息保留时长(秒)，
                    // 推送当前用户不在线时，为该用户保留多长时间的离线消息，以便其上线时再次推送。
                    // 默认 86400 （1 天），最长 10 天。设置为 0 表示不保留离线消息，只有推送当前在线的用户可以收到
                    // 这里设置为 1 仅作为示例

                    // 'time_to_live' => 1,

                    // apns_production: 表示APNs是否生产环境，
                    // True 表示推送生产环境，False 表示要推送开发环境；如果不指定则默认为推送生产环境

                    'apns_production' => false,

                    // big_push_duration: 表示定速推送时长(分钟)，又名缓慢推送，把原本尽可能快的推送速度，降低下来，
                    // 给定的 n 分钟内，均匀地向这次推送的目标用户推送。最大值为1400.未设置则不是定速推送
                    // 这里设置为 1 仅作为示例

                    // 'big_push_duration' => 1
                ))
                ->send();
            print_r($response);

        } catch (\JPush\Exceptions\APIConnectionException $e) {
            // try something here
            print $e;
        } catch (\JPush\Exceptions\APIRequestException $e) {
            // try something here
            print $e;
        }
    }


    /*
     * 离线操作数据处理
     */
    public function dealOrder(){
        $res =  M('RestaurantstyyLog')->add(array('content'=>$GLOBALS['HTTP_RAW_POST_DATA'],'create_time'=>time()));
        if($res){
            $this->ajaxReturn(array('code' => 200,'message' => '保存成功','data'=>''));
        }else{
            $this->ajaxReturn(array('code' => 201,'message' => '保存失败','data'=>''));
        }
    }



    /**
     * 校园卡支付
     */
    public function saveOrder()
    {

        //pay_type:4-》新版校园卡
        $post = $this->_request();

        //日志
        wLog(date("Y-m-d H:i:s")." saveOrder-1-post: ".var_export($post,true),"styy");
        $key = $post['card_num'].'-'.date('Y-m-d',time());
        $orderId = $post['order_id'];
        //如果是卡在这里的话,就简单了。如何得到档口
        $da = date("w");

//         D('')=

        $notice=' ';//备注

        if (!$orderId) {
            //日志
            wLog(date("Y-m-d H:i:s")." saveOrder-2-orderId ".'参数错误',"styy");
            $this->ajaxReturn(array('code' => 201, 'message' => '参数错误'));
        }


        $order = $this->mOrder->where(array('order_id' => $orderId))->find();
        //日志
        wLog(date("Y-m-d H:i:s")." saveOrder-2.1-order ".var_export($order,true),"styy");
        if (!$order) {
            //日志
            wLog(date("Y-m-d H:i:s")." saveOrder-2.2-order ". '订单不存在',"styy");
            $this->ajaxReturn(array('code' => 202, 'message' => '订单不存在'));
        }

        if ($order['status'] == 1 || $order['status'] == 2) {
            //日志
            wLog(date("Y-m-d H:i:s")." saveOrder-2.3-order ". '该订单已支付',"styy");
            $this->ajaxReturn(array('code' => 203, 'message' => '该订单已支付'));
        }


        //是否启用密码
        if($post['password']){
            $res = $this->doPwd($post['card_num'],$post['password']);
            if($res['status'] != "S"){
                //日志
                wLog(date("Y-m-d H:i:s")." saveOrder-3-password ".var_export($res,true).'密码错误',"styy");
                $this->ajaxReturn(array('code' => 206, 'message' => '密码错误'));
            }
        }else{
            $quota = RedisService::get($key);
            if($quota){
                if($quota>=50){
                    //日志
                    wLog(date("Y-m-d H:i:s")." saveOrder-4-quota ".var_export($quota,true).'达到限额,输入密码',"styy");
                    $this->ajaxReturn(array('code' => 207, 'message' => '达到限额,输入密码'));
                }
            }else{
                RedisService::set($key,0,72000);
            }
        }

        $re = $this->_campusCardPay($post['card_num'], $order['goods_amount'], $order['order_sn'],$orderId);
        //日志
        wLog(date("Y-m-d H:i:s")." saveOrder-5-re ".var_export($re,true),"styy");
        if (!$re) {
            //日志
            wLog(date("Y-m-d H:i:s")." saveOrder-5.1-re ".var_export($re,true).'支付失败',"styy");
            $this->ajaxReturn(array('code' => 204, 'message' => '支付失败'));
        }

        if ($re['status'] != 'S') {
            //日志
            wLog(date("Y-m-d H:i:s")." saveOrder-6-re ".var_export($re,true).'支付失败',"styy");
            $this->ajaxReturn(array('code' => 204, 'message' => $re['message']));
        }

        $this->notify1($orderId,$type ='oneCard');
        //判断打折价格是否是浮点数
        $order1 = $this->mOrder->where(array('order_id' => $orderId))->find();
        if(is_float($order1['order_amount'])){
            RedisService::incrByFloat($key,$order1['order_amount']);
        }else{
            RedisService::incr($key,$order1['order_amount']);
        }


        $resInfo = $this->orderInfo($orderId);

        $resInfo['account']=$re['message']['account'];
        $resInfo['balance']=$re['message']['balance'];

        //判断是否同时存在西餐和料理
//        $sGoods = Service('RestaurantStyy/BaseOrder');
//        $isHaveWestAndDeal=$sGoods->haveWestAndDeal($orderId);
//        if($isHaveWestAndDeal && $isHaveWestAndDeal==1){
//            $notice='请到西餐窗口取餐';
//        }elseif($isHaveWestAndDeal && $isHaveWestAndDeal==2){
//            $notice='请到西餐窗口取餐';
//        }elseif($isHaveWestAndDeal && $isHaveWestAndDeal==3){
//            $notice='请到料理窗口取餐';
//        }
        $array = array('T11017CS00277','T11017CS00305','T11017CS00317','T11717BJ00146'); //1楼
        $array1 = array('T11017CS00308','T11017CS00298','T110175U00042','T11017CS00304'); //2楼

        $iPadId = session('iPadId');
        if(in_array($iPadId,$array)){ //1楼
            $notice='呼叫器提示后请到取餐窗口取餐';
        }elseif(in_array($iPadId,$array1)){
            $notice=' ';
        }
        $resInfo['notice']=$notice;
        //日志
        wLog(date("Y-m-d H:i:s")." saveOrder-7-resInfo ".var_export($resInfo,true),"styy");

        $this->ajaxReturn(array('code' => 200,'message' => '支付成功','data'=>$resInfo));


    }

    /**
     * 校园卡效验密码
     */
    public function doPwd($account,$password){
        $type = 'cardid';
//        $type = 'acc';
        //解析$account

        $account = $this->_analysisAccount($account);

        if(!$account){
            return array("status"=>"F","message"=>$account);
        }
        $campuscard = M("Campuscard")->where(array("account_id" => $this->accountId, "status" => 1))->find();
        vendor("CampusCard.CampusApiNew");
        $ser = new CampusApiNew($campuscard);
        $res = $ser->checkQueryPwd($type,$account,$password);

        if($res['status'] != 'S'){
            return array("status"=>"F","message"=>$res['message']);
        }

        if($res['data']['retcode'] != 0){
            return array("status"=>"F","message"=>$res['errmsg']);
        }
        return array("status"=>"S","message"=>'密码效验成功');
    }


    /**
     * 校园卡支付
     * @param $account
     * @param $money
     * @Auth    : piyechao
     * @Now     :2017/12/15 19:13
     */
    private function _campusCardPay($account,$money,$order_no,$orderId)
    {

        //解析$account

        $account = $this->_analysisAccount($account);
        //日志
        wLog(date("Y-m-d H:i:s")." _campusCardPay-0-account ".var_export($account,true),"styy");
        if(!$account){
            //日志
            wLog(date("Y-m-d H:i:s")." _campusCardPay-1-account ".'卡号解析失败',"styy");
            return array("status"=>"F","message"=>'卡号解析失败');
        }

        $sOrder = Service('RestaurantStyy/BaseOrder');

        $campuscard = M("Campuscard")->where(array("account_id" => $this->accountId, "status" => 1))->find();
        $mercacc = $campuscard['toaccount'];//'2001308';//商户号
//        $type = 'acc';   //号码类型
        $type = 'cardid';   //号码类型
        $mes = '001';       //账号类型
        vendor("CampusCard.CampusApiNew");
        $ser = new CampusApiNew($campuscard);
        $accountInfo = $ser->getAccountInfo($type,$account);
        if($accountInfo['status'] !== 'S'){
            //日志
            wLog(date("Y-m-d H:i:s")." _campusCardPay-1-accountInfo ".var_export($accountInfo,true),"styy");
            return array("status"=>"F","message"=>$accountInfo['message']);
        }
        if(!isset($accountInfo['data'][0]['account'])){
            //日志
            wLog(date("Y-m-d H:i:s")." _campusCardPay-2-accountInfo ".var_export($accountInfo,true),"styy");
            return array("status"=>"F","message"=>'查询失败');
        }
        //查找卡的类型
        $discount = M('RestaurantstyyCourier');
        $orderGoods = M('RestaurantstyyOrderGoods');
        $dis = $discount->where(array('card_num'=>$accountInfo['data'][0]['cardtype'],'cut_off'=>0,'status'=>1))->getField('discount');
        //日志
        wLog(date("Y-m-d H:i:s")." _campusCardPay-3-dis ".var_export($dis,true),"styy");
        $data = array(
            'user_name'=>$accountInfo['data'][0]['name'],
            'card_number'=>$accountInfo['data'][0]['account'],
            'order_amount'=>$money//原价
        );
        //日志
        wLog(date("Y-m-d H:i:s")." _campusCardPay-4-money ".var_export($money,true),"styy");
        $goods = $orderGoods->where(array('order_id'=>$orderId))->field('og_id,goods_price')->select();
        //判断是否打折
        if($dis){
            $money = $money*$dis;//商品打折价格
            $data['order_amount'] = $money;
            foreach($goods as $k=>$v){
                $info = array();
                $info = array(
                    'og_id'=>$v['og_id'],
                    'disconut_price'=>round($v['goods_price']*$dis,2),
                    'disconut'=>$dis
                );
                $orderGoods->save($info);
            }
        }else{
            foreach($goods as $k=>$v){
                $info = array();
                $info = array(
                    'og_id'=>$v['og_id'],
                    'disconut_price'=>$v['goods_price'],
                    'disconut'=>0
                );
                wLog(date("Y-m-d H:i:s")." _campusCardPay-4.2-info ".var_export($info,true),"styy");
                $orderGoods->save($info);
            }
        }

        //日志
        wLog(date("Y-m-d H:i:s")." _campusCardPay-5-money ".var_export($money,true),"styy");

        $updateOrder = $this->mOrder->where(array('order_id'=>$orderId))->save($data);

        //日志
        wLog(date("Y-m-d H:i:s")." _campusCardPay-6-mOrder_sql ".var_export($this->mOrder->_sql(),true),"styy");

        if (!$updateOrder){
            //日志
            wLog(date("Y-m-d H:i:s")." _campusCardPay-7-updateOrder ".var_export($updateOrder,true).'-打折失败',"styy");
            return array("status"=>"F","message"=>'打折失败');
        }

        wLog(date("Y-m-d H:i:s")." _campusCardPay-8-order_no ".var_export($order_no,true),"styy");

        $res = $ser->tradePay($accountInfo['data'][0]['account'],$money,$mes,$mercacc,'',$order_no);
        //日志
        wLog(date("Y-m-d H:i:s")." _campusCardPay-8-res ".var_export($res,true),"styy");
        if($res['status'] != 'S'){
            //日志
            wLog(date("Y-m-d H:i:s")." _campusCardPay-8-res_status ".var_export($res['status'],true),"styy");
            return array("status"=>"F","message"=>$res['message']);
        }
        //获得账号余额
        $accInfo = $ser->getAccInfo($accountInfo['data'][0]['account']);
        //日志
        wLog(date("Y-m-d H:i:s")." _campusCardPay-9-accInfo ".var_export($accInfo,true),"styy");
        if($accInfo['status'] != 'S' || !isset($accInfo['data']['balance'])){
            //日志
            wLog(date("Y-m-d H:i:s")." _campusCardPay-10-accInfo ".'查询余额失败',"styy");
            return array("status"=>"F","message"=>'查询余额失败');
        }

        return array("status"=>"S","message"=>array('account'=>$accountInfo['data'][0]['account'],'balance'=>$accInfo['data']['balance']/100));
    }



    /**
     * 解析校园卡账户
     * @param $account
     * @return bool|number
     * @Auth    : piyechao
     * @Now     :2017/12/19 9:12
     */
    private function _analysisAccount($account)
    {
        if(strlen($account) !== 8){
            return false;
        }
        $str1 = substr($account,0,2);
        $str2 = substr($account,2,2);
        $str3 = substr($account,4,2);
        $str4 = substr($account,6,2);
        $account = hexdec($str4.$str3.$str2.$str1);
        return $account;
    }
}